<template>
  <div>
    <div class="writers-container">
      <h1 class="title-common">天堂应该是图书馆的模样 · 这里收藏它的建造者们</h1>
      <div class="search-container">
        <div class="search-box">
          <img 
            src="@/assets/img/find.png"
            class="search-icon"
            alt="搜索"
            @click="triggerSearch"
          >
          <input 
            type="text" 
            v-model="searchQuery"
            @keyup.enter="triggerSearch"
            :placeholder="placeholder"
            @focus="placeholder = ''"
            @blur="placeholder = '搜索您感兴趣的作家...'"
          >
          <button 
            class="btn-common btn-secondary" 
            :class="{ active: searchQuery }"
            @click="triggerSearch"
            :disabled="!searchQuery"
          >
            <span class="arrow">&uarr;</span>
          </button>
        </div>
      </div>
      <div class="writers-grid" :class="{ 'search-result': hasSearched && total === 0 }">
        <div
          v-for="(writer, idx) in displayWriters"
          :key="writer.id || 'add'"
          class="writer-item"
          @click="handleWriterClick(writer, idx)"
          style="cursor: pointer;"
        >
          <template v-if="writer.isAdd">
            <div class="add-icon">+</div>
            <h3>增加您喜欢的作家</h3>
          </template>
          <template v-else>
            <img
              :src="getAvatar(writer.avatar_path)"
              :alt="writer.name"
              class="writer-img"
            />
            <h3>{{ writer.name }}</h3>
          </template>
        </div>
      </div>
      
      <!-- 使用新的翻页组件 -->
      <PaginationBar
        :current-page="page"
        :total="total"
        :page-size="pageSize"
        :show-pagination="total > pageSize"
        @page-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script>
import PaginationBar from '@/components/PaginationBar.vue'

export default {
  name: 'Home',
  components: {
    PaginationBar
  },
  data() {
    return {
      writers: [],
      total: 0,
      page: 1,
      pageSize: 5,
      searchQuery: '',
      placeholder: '搜索您感兴趣的作家...',
      searchTimeout: null,
      isManualSearch: false,
      hasSearched: false
    }
  },
  watch: {
    searchQuery() { 
      return
    }
  },
  computed: {
    displayWriters() {
      if (this.hasSearched && this.total === 0) {
        return [
          { isAdd: true, isSearchResult: true }
        ]
      }
      if (this.total === 0) {
        return [
          { id: 'self', name: '我们自己', avatar_path: '', isAdd: false },
          { isAdd: true }
        ]
      }
      const arr = [...this.writers]
      arr.push({ isAdd: true })
      return arr
    }
  },
  methods: {
    async fetchWriters() {
      try {
        const res = await this.$axios.get('/api/writers', {
          params: { 
            page: this.page, 
            pageSize: this.pageSize,
            search: this.searchQuery
          }
        })
        this.writers = res.data.writers
        this.total = res.data.total
      } catch (error) {
        console.error('获取作家列表失败:', error)
      }
    },
    triggerSearch() {
      this.handleSearch()
    },
    handleSearch() {
      if (this.searchQuery || this.searchQuery === '') {
        if (this.searchTimeout) {
          clearTimeout(this.searchTimeout)
        }
        this.searchTimeout = setTimeout(() => {
          this.page = 1
          this.hasSearched = true
          this.fetchWriters()
        }, 300)
      }
    },
    getAvatar(path) {
      if (!path) return require('@/assets/img/Literature Trace.png')
      if (typeof path === 'string' && path.startsWith('/img/')) {
        return `http://localhost:3000${path}`
      }
      try {
        return require(`@/assets/img/${path}`)
      } catch {
        return require('@/assets/img/Literature Trace.png')
      }
    },
    handleWriterClick(writer, idx) {
      console.log(idx)
      if (writer.isAdd) {
        this.$router.push('/edit-writer')
      } else if (writer.id && writer.id !== 'self') {
        this.$router.push({ name: 'Experience', params: { id: writer.id } })
      }
    },
    handlePageChange(page) {
      this.page = page
      this.fetchWriters()
    }
  },
  mounted() {
    this.fetchWriters()
  }
}
</script>

<style scoped>
@import '../assets/css/common.css';
@import '../assets/css/home.css';

.writers-container h1 {
  display: block; 
  margin-top: 10px !important;
  padding-bottom: 10px;
  border-bottom: #3F6580 solid 1px;
  margin-bottom: 20px;
}

.search-button .arrow {
  display: inline-block;
  margin-top: -2px;
}

.writers-grid.search-result {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.writers-grid.search-result .writer-item {
  margin: 0;
}
</style>
